﻿
//binding href: val instead of attr binding
ko.bindingHandlers.href = {
    update: function (element, valueAccessor) {
        ko.bindingHandlers.attr.update(element, function () {
            return { href: valueAccessor() }
        });
    }
};

//binding src: val instead of attr binding
ko.bindingHandlers.src = {
    update: function (element, valueAccessor) {
        ko.bindingHandlers.attr.update(element, function () {
            return { src: valueAccessor() }
        });
    }
};

//binding chosen mutilple
ko.bindingHandlers.chosen = {
    init: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        //$(element).addClass('chzn-select');
        $(element).chosen();
    },
    update: function (element, valueAccessor, allBindingsAccessor, viewModel) {
        //$(element).trigger("liszt:updated");
        $(element).trigger("chosen:updated");
    }
};

//binding hidden element instead of visible: false
ko.bindingHandlers.hidden = {
    update: function (element, valueAccessor) {
        var value = ko.utils.unwrapObservable(valueAccessor());
        ko.bindingHandlers.visible.update(element, function () { return !value; });
    }
};

//combine value and valueupdate binding
ko.bindingHandlers.instantValue = {
    init: function (element, valueAccessor, allBindings) {
        var newAllBindings = function () {
            // for backwards compatibility w/ knockout  < 3.0
            return ko.utils.extend(allBindings(), { valueUpdate: 'afterkeydown' });
        };
        newAllBindings.get = function (a) {
            return a === 'valueupdate' ? 'afterkeydown' : allBindings.get(a);
        };
        newAllBindings.has = function (a) {
            return a === 'valueupdate' || allBindings.has(a);
        };
        ko.bindingHandlers.value.init(element, valueAccessor, newAllBindings);
    },
    update: ko.bindingHandlers.value.update
};


//time ago knockout binding EX: data-bind="timeAgo: dateCreated"
function toTimeAgo(dt) {
    var secs = (((new Date()).getTime() - dt.getTime()) / 1000),
        days = Math.floor(secs / 86400);

    return days === 0 && (
        secs < 60 && "just now" ||
            secs < 120 && "a minute ago" ||
            secs < 3600 && Math.floor(secs / 60) + " minutes ago" ||
            secs < 7200 && "an hour ago" ||
            secs < 86400 && Math.floor(secs / 3600) + " hours ago") ||
        days === 1 && "yesterday" ||
        days < 31 && days + " days ago" ||
        days < 60 && "one month ago" ||
        days < 365 && Math.ceil(days / 30) + " months ago" ||
        days < 730 && "one year ago" ||
        Math.ceil(days / 365) + " years ago";
};

ko.bindingHandlers.timeAgo = {
    update: function (element, valueAccessor) {
        var val = ko.utils.unwrapObservable(valueAccessor()),
            date = new Date(val), // WARNING: this is not compatibile with IE8
            timeAgo = toTimeAgo(date);
        return ko.bindingHandlers.html.update(element, function () {
            return '<time datetime="' + encodeURIComponent(val) + '">' + timeAgo + '</time>';
        });
    }
};


//Binding currency  .EX: data-bind="currency: price, symbol: '€'"
ko.bindingHandlers.currency = {
    symbol: ko.observable('$'),
    update: function (element, valueAccessor, allBindingsAccessor) {
        return ko.bindingHandlers.text.update(element, function () {
            var value = +(ko.utils.unwrapObservable(valueAccessor()) || 0),
                symbol = ko.utils.unwrapObservable(allBindingsAccessor().symbol === undefined
                            ? allBindingsAccessor().symbol
                            : ko.bindingHandlers.currency.symbol);
            return symbol + value.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,");
        });
    }
};;
//get param and hash
$.extend({
    loadPreviewImg: function (input, target) {
        var reader = new FileReader();
        reader.onload = function (e) {
            target.attr('src', e.target.result);
        }
        reader.readAsDataURL(input.files[0]);

    },
    getUrlVars: function (sParam) {
        var sPageURL = window.location.hash.substring(1);
        var sURLVariables = sPageURL.split('&');
        for (var i = 0; i < sURLVariables.length; i++) {
            var sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] === sParam) {
                return sParameterName[1];
            }
        }
    },
    replaceUrl: function (page, searchString) {
        var queryParameters = {};
        queryParameters['page'] = page;
        queryParameters['searchString'] = searchString;
        location.hash = $.param(queryParameters);
    },
    getUrlParams: function (sParam) {
        var sPageURL = window.location.search.substring(1);
        var sURLVariables = sPageURL.split('&');
        for (var i = 0; i < sURLVariables.length; i++) {
            var sParameterName = sURLVariables[i].split('=');
            if (sParameterName[0] === sParam) {
                return sParameterName[1];
            }
        }
    },
});


var TebbeeChart = function () {
    return {
        init: function (mem, pub, element) {
            var e = [[1, "Tháng 1"], [2, "Tháng 2"], [3, "Tháng 3"], [4, "Tháng 4"], [5, "Tháng 5"], [6, "Tháng 6"],
                [7, "Tháng 7"], [8, "Tháng 8"], [9, "Tháng 9"], [10, "Tháng 10"], [11, "Tháng 11"], [12, "Tháng 12"]];
            $.plot(element,
                [{
                    label: "Member",
                    data: mem,
                    lines: {
                        show: !0,
                        fill: !0,
                        fillColor: {
                            colors: [{ opacity: .25 },
                                { opacity: .25 }]
                        }
                    }, points: {
                        show: !0,
                        radius: 6
                    }
                },
                {
                    label: "Publisher",
                    data: pub,
                    lines: {
                        show: !0,
                        fill: !0,
                        fillColor: {
                            colors: [{ opacity: .15 },
                                { opacity: .15 }]
                        }
                    }, points: {
                        show: !0,
                        radius: 6
                    }
                }],
                {
                    colors: ["#3498db", "#333333"],
                    legend: {
                        show: !0, position: "nw",
                        margin: [15, 10]
                    }, grid: {
                        borderWidth: 0,
                        hoverable: !0,
                        clickable: !0
                    }, yaxis: {
                        ticks: 4,
                        tickColor: "#eeeeee"
                    }, xaxis: {
                        ticks: e,
                        tickColor: "#ffffff"
                    }
                });
            var u = null, x = null;
            element.bind("plothover",
                function (o, i, t) {
                    if (t) {
                        if (u !== t.dataIndex) {
                            u = t.dataIndex,
                            $("#chart-tooltip").remove();
                            var l = (t.datapoint[0], t.datapoint[1]);
                            x = 1 === t.seriesIndex ? "<strong>" + l + "</strong> Người Đăng QC" :
                                "<strong>" + l + "</strong> Thành Viên",
                            $('<div id="chart-tooltip" class="chart-tooltip">' + x + "</div>").css({ top: t.pageY - 45, left: t.pageX + 5 }).appendTo("body").show()
                        }
                    } else $("#chart-tooltip").remove(), u = null
                })
        },
        ViewLikeHits: function (views, likes, hits, t) {
            var e = [[1, "Tháng 1"], [2, "Tháng 2"], [3, "Tháng 3"], [4, "Tháng 4"], [5, "Tháng 5"], [6, "Tháng 6"],
                [7, "Tháng 7"], [8, "Tháng 8"], [9, "Tháng 9"], [10, "Tháng 10"], [11, "Tháng 11"], [12, "Tháng 12"]];
            $.plot(t,
                [{ label: "Thích", data: likes },
                { label: "Xem", data: views },
                { label: "Truy Cập", data: hits}],
                {
                    colors: ["#f1c40f", "#f39c12"],
                    series: {
                        stack: !0, lines: {
                            show: !0,
                            fill: !0
                        }
                    }, lines: {
                        show: !0,
                        lineWidth: 0,
                        fill: !0,
                        fillColor: {
                            colors: [{ opacity: .75 },
                                { opacity: .75 }]
                        }
                    },
                    legend: {
                        show: !0,
                        position: "nw",
                        margin: [15, 10],
                        sorted: !0
                    },
                    grid: { borderWidth: 0 },
                    yaxis: {
                        ticks: 4,
                        tickColor: "#eeeeee"
                    },
                    xaxis: {
                        ticks: e,
                        tickColor: "#ffffff"
                    }
                })
            //$.plot(t,
            //    [{
            //        data: views,
            //        lines: {
            //            show: !0,
            //            fill: !1
            //        },
            //        points: {
            //            show: !0,
            //            radius: 6,
            //            fillColor: "#cccccc"
            //        }
            //    }, {
            //        data: likes,
            //        lines: {
            //            show: !0,
            //            fill: !1
            //        }, points: {
            //            show: !0,
            //            radius: 6,
            //            fillColor: "#ffffff"
            //        }
            //    }, {
            //        data: hits,
            //        lines: {
            //            show: !0,
            //            fill: !1
            //        }, points: {
            //            show: !0,
            //            radius: 6,
            //            fillColor: "gray"
            //        }
            //    }], {
            //        colors: ["#ffffff", "#353535"],
            //        legend: { show: !1 },
            //        grid: {
            //            borderWidth: 0,
            //            hoverable: !0,
            //            clickable: !0
            //        },
            //        yaxis: { show: !1 },
            //        xaxis: {
            //            show: !1,
            //            ticks: e
            //        }
            //    });

            //var a = null,
            //    s = null;
            //t.add(t).bind("plothover",
            //    function (o, i, t) {
            //        if (t) {
            //            if (a !== t.dataIndex) {
            //                a = t.dataIndex,
            //                $("#chart-tooltip").remove();
            //                var l = (t.datapoint[0], t.datapoint[1]),
            //                    f = t.series.xaxis.options.ticks[t.dataIndex][1];
            //                s = 1 === t.seriesIndex ? "<strong>" + l + "</strong> Lượt Thích Trong <strong>" + f + "</strong>" :
            //                    s = 2 === t.seriesIndex ? "<strong>" + l + "</strong> Lượt Truy Cập Trong <strong>" + f + "</strong>" :
            //                    "<strong>" + l + "</strong> Lượt Xem Trong <strong>" + f + "</strong>",
            //                $('<div id="chart-tooltip" class="chart-tooltip">' + s + "</div>").css({ top: t.pageY - 50, left: t.pageX - 50 }).appendTo("body").show()
            //            }
            //        } else $("#chart-tooltip").remove(),
            //            a = null
            //    })
        }
    }
}();